<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <!-- 插入到left插槽位置 -->
        <template #left>
          <span>本月: 社保在缴 公积金在缴</span>
        </template>
        <!-- 插入到right插槽位置 -->
        <template #right>
          <el-button
            v-allow="'import_excel'"
            type="warning"
            size="small"
            @click="$router.push('/import')"
          >导入excel</el-button>
          <el-button
            v-allow="'export_excel'"
            type="danger"
            size="small"
            @click="exportExcel"
          >导出excel</el-button>
          <el-button
            v-allow="'addEmployee'"
            type="primary"
            size="small"
            @click.native="hAdd"
          >新增员工</el-button>
        </template>
      </page-tools>
      <el-card style="margin-top: 10px;">
        <el-table border :data="employeesList">
          <el-table-column label="序号" type="index" width="80px" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="员工头像" width="120">
            <template #default="{row}">
              <img v-imageerror="require('@/assets/common/head.jpg')" :src="row.staffPhoto" style="height:100px" @click="showCode(row.staffPhoto)">
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式">
            <template slot-scope="scope">
              {{ ['未知','正式','非正式'][scope.row.formOfEmployment] }}
            </template>
          </el-table-column>
          <!-- <el-table-column label="聘用形式" prop="formOfEmployment" /> -->

          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" />
          <el-table-column label="操作" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push('/employees/detail?id='+row.id)">查看</el-button>
              <el-button type="text" size="small" @click="hAssignRole(row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :current-page="q.page"
            :page-sizes="[2, 5, 10, 20]"
            :page-size="q.size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
      <el-dialog title="新增员工" :visible.sync="showDialog">

        <add-form v-if="showDialog" @success="hSuccess" @close="hClose" />
      </el-dialog>
      <el-dialog title="头像二维码" :visible.sync="showCodeDialog">

        <el-row type="flex" justify="center">
          <canvas ref="codeCanvas" />
        </el-row>
      </el-dialog>
      <el-dialog :visible.sync="showDialogRole" title="分配角色">
        <assign-role v-if="showDialogRole" :cur-id="curId" @close="showDialogRole=false" />
      </el-dialog>

    </div>
  </div>
</template>
<script>
import AssignRole from './assignRole'
import QrCode from 'qrcode'
import { delEmployee, getEmployeesList } from '@/api/employee'
import AddForm from './AddForm'
import { enTransZh } from '@/utils'
export default {
  components: { AddForm, AssignRole },
  data() {
    return {
      q: {
        page: 1,
        size: 10
      },
      employeesList: [],
      total: 10,
      showDialog: false,
      showCodeDialog: false,
      showDialogRole: false,
      curId: ''
    }
  },
  created() {
    this.loadEmployeesList()
  },
  methods: {
    hAssignRole(id) {
      this.curId = id
      this.showDialogRole = true
    },
    showCode(url) {
      if (!url) return this.$message.error('请上传员工头像')
      this.showCodeDialog = true
      this.$nextTick(() => {
        const canvas = this.$refs.codeCanvas
        QrCode.toCanvas(canvas, url)
      })
    },
    exportExcel() {
      import('@/vendor/Export2Excel').then(async excel => {
        // const tHeader = ['Id', 'Title', 'Author', 'Readings', 'Date']
        // const filterVal = ['id', 'title', 'author', 'pageviews', 'display_time']
        // const list = this.list
        // const data = this.formatJson(filterVal, list)
        await this.loadEmployeesList()
        const { header, data } = enTransZh(this.employeesList)
        excel.export_json_to_excel({
          header,
          data,
          filename: this.filename,
          autoWidth: true,
          bookType: this.bookType
        })
      })
    },
    async loadEmployeesList() {
      try {
        const res = await getEmployeesList(this.q)
        console.log(res)
        if (res.code !== 10000) return
        this.$message.success(res.message)
        this.total = res.data.total
        this.employeesList = res.data.rows
      } catch (error) {
        console.log(error)
      }
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.q.size = val
      this.q.page = 1
      this.loadEmployeesList()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.q.page = val
      this.loadEmployeesList()
    },
    hSuccess() {
      this.showDialog = false
      this.loadEmployeesList()
      this.total++
      // 最后一页
      this.q.page = Math.ceil(this.total / this.q.size)
    },
    hClose() {
      this.showDialog = false
    },
    async hDel(id) {
      this.$confirm('确认删除该员工?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const res = await delEmployee(id)
        if (res.code === 10000) {
          this.$message.success(res.message)
          if (this.employeesList.length === 1) {
            this.q.page--
            if (this.q.page <= 0) {
              this.q.page = 1
            }
          }
          this.loadEmployeesList()
        }
      }).catch((error) => {
        this.$message.error(error)
      })
    },
    hAdd() {
      this.showDialog = true
    }
  }
}
</script>
